/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uniriotec.pm.trabalho2.dao.postgresql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;

/**
 *
 * @author albertoapr
 */
public class PostgresqlDB {
   
	private String url = "jdbc:postgresql://localhost:5432/prova";
	private String user = "admin";
	private String password = "admin";
	private String postgresqlDriver = "org.postgresql.Driver";
	private Connection connection;

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPostgresqlDriver() {
        return postgresqlDriver;
    }

    public void setPostgresqlDriver(String postgresqlDriver) {
        this.postgresqlDriver = postgresqlDriver;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
        
        protected void criaConexao(Boolean autocommit) throws ClassNotFoundException,
			SQLException {
		try {
			Class.forName(postgresqlDriver);
		} catch (ClassNotFoundException e) {
			throw e;
		}
		try {
			connection = DriverManager.getConnection(url, user, password);
			connection.setAutoCommit(autocommit);
		} catch (SQLException e) {
			throw e;
		}
	}

	/**
	 * Fecha conexao.
	 * 
	 * @throws SQLException
	 *             the SQL exception
	 */
	protected void fechaConexao() throws SQLException {
		try {
			connection.close();
		} catch (SQLException e) {
			throw e;
		}
	}

	/**
	 * Recupera sequence.
	 * 
	 * @return the integer
	 * @throws ClassNotFoundException
	 *             the class not found exception
	 * @throws SQLException
	 *             the SQL exception
	 */
	@SuppressWarnings("unused")
	private Integer recuperaSequence() throws ClassNotFoundException,
			SQLException {

		this.criaConexao(false);
		String sql = "select nextval('sq_Revendedor') as id";
		PreparedStatement stmt = null;
		ResultSet rs = null;
		Integer identificador = null;

		try {
			stmt = connection.prepareStatement(sql);
			rs = stmt.executeQuery();
			if (rs.next()) {
				identificador = rs.getInt("id");
			}

		} catch (SQLException e) {
			throw e;

		} finally {
			try {
				stmt.close();
				rs.close();
				this.fechaConexao();

			} catch (SQLException e) {
				throw e;
			}

		}
		return identificador;
	}
        
}
